/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

package it.coraci.anag.gui.docs;

import it.coraci.anag.db.mongo.controllers.MongoDocumentJpaController;
import it.coraci.anag.db.mongo.entities.Attribute;
import it.coraci.anag.db.mongo.entities.MongoDocument;
import it.coraci.anag.db.sql.controllers.IDDocTypeJpaController;
import it.coraci.anag.db.sql.controllers.IDDocumentJpaController;
import it.coraci.anag.db.sql.controllers.PersonJpaController;
import it.coraci.anag.db.sql.entities.IDDocType;
import it.coraci.anag.db.sql.entities.IDDocument;
import it.coraci.anag.db.sql.entities.Person;
import java.awt.Rectangle;
import java.beans.Beans;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.persistence.Persistence;
import javax.swing.RepaintManager;

/**
 *
 * @author Luca
 */
public class NewDocFrame extends javax.swing.JFrame {

    private List<ParamPanel> paramsPanel = new ArrayList<ParamPanel>();
    private Person selectedPerson = null;
    private IDDocType selectedDocType = null;
    
    /**
     * Creates new form NewDocFrame
     */
    public NewDocFrame() {
        initComponents();
        if (!Beans.isDesignTime()) {
            IDDocTypeJpaController cc = new IDDocTypeJpaController(Persistence.createEntityManagerFactory("dbAnagBasePU"));
            List<IDDocType> types = cc.findIDDocTypeEntities();
            for (IDDocType iDDocType : types) {
                this.docTypeComboBoxModel1.addElement(iDDocType);
            }
        }
    }

    public void setSelectedPerson(Person selectedPerson) {
        this.selectedPerson = selectedPerson;
    }

    public Person getSelectedPerson() {
        return selectedPerson;
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        docTypeComboBoxRenderer1 = new it.coraci.anag.gui.docs.mr.DocTypeComboBoxRenderer();
        docTypeComboBoxModel1 = new it.coraci.anag.gui.docs.mr.DocTypeComboBoxModel();
        jLabel1 = new javax.swing.JLabel();
        jComboBox1 = new javax.swing.JComboBox();
        jPanel2 = new javax.swing.JPanel();
        jPanel1 = new javax.swing.JPanel();
        jButton1 = new javax.swing.JButton();

        docTypeComboBoxRenderer1.setText("docTypeComboBoxRenderer1");

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);

        jLabel1.setText("Documento:");

        jComboBox1.setModel(docTypeComboBoxModel1);
        jComboBox1.setRenderer(docTypeComboBoxRenderer1);
        jComboBox1.addItemListener(new java.awt.event.ItemListener() {
            public void itemStateChanged(java.awt.event.ItemEvent evt) {
                jComboBox1ItemStateChanged(evt);
            }
        });

        jPanel1.setLayout(new javax.swing.BoxLayout(jPanel1, javax.swing.BoxLayout.Y_AXIS));

        jButton1.setText("Salva");
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
        jPanel2.setLayout(jPanel2Layout);
        jPanel2Layout.setHorizontalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel2Layout.createSequentialGroup()
                        .addGap(0, 0, Short.MAX_VALUE)
                        .addComponent(jButton1)))
                .addContainerGap())
        );
        jPanel2Layout.setVerticalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, 210, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 8, Short.MAX_VALUE)
                .addComponent(jButton1)
                .addContainerGap())
        );

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 90, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jComboBox1, 0, 286, Short.MAX_VALUE)
                .addContainerGap())
            .addComponent(jPanel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 31, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jComboBox1, javax.swing.GroupLayout.PREFERRED_SIZE, 20, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jPanel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void jComboBox1ItemStateChanged(java.awt.event.ItemEvent evt) {//GEN-FIRST:event_jComboBox1ItemStateChanged
        System.out.println("item selected");
        Object selectedItem = this.jComboBox1.getSelectedItem();
        for (ParamPanel paramPanel : paramsPanel) {
            this.jPanel1.remove(paramPanel);
        }
        paramsPanel.clear();
        if(selectedItem!=null && selectedItem instanceof IDDocType){
            String type = ((IDDocType)selectedItem).getType();
            this.selectedDocType = ((IDDocType)selectedItem);
            System.out.println("type = "+type);
            List<String> params = ((IDDocType)selectedItem).getParams();
            for (String param : params) {
                ParamPanel p = new ParamPanel(new Attribute(param, ""));
                paramsPanel.add(p);
                this.jPanel1.add(p);
//                p.repaint();
            }
        }
        
        jPanel2.invalidate();
        jPanel2.revalidate();
        jPanel2.repaint();
//        Rectangle progressRect = jPanel2.getBounds();
//        progressRect.x = 0;
//        progressRect.y = 0;
//        jPanel2.paintImmediately(progressRect);

//        RepaintManager rp = RepaintManager.currentManager(this.jPanel1);
//            rp.markCompletelyDirty(this.jPanel1);
//            rp.validateInvalidComponents();
//            rp.paintDirtyRegions();
////        this.jPanel1.invalidate();
//        this.jPanel1.revalidate();
        
//        this.repaint();
    }//GEN-LAST:event_jComboBox1ItemStateChanged

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
        if(selectedPerson!=null && selectedDocType != null){
            IDDocument doc = new IDDocument();
            MongoDocument mongoDoc = new MongoDocument();
            List<Attribute> attributes = new ArrayList<>();
            for (ParamPanel paramPanel : paramsPanel) {
                attributes.add(paramPanel.getAttribute());
            }
            mongoDoc.setValues(attributes);
            MongoDocumentJpaController cc = new MongoDocumentJpaController(Persistence.createEntityManagerFactory("nosqlDBPU"));
            cc.create(mongoDoc);
            String id = mongoDoc.getId();
            System.out.println("created ID = "+id);
            doc.setType(selectedDocType);
            doc.setFileID(id);
            selectedPerson.addIdDocument(doc);
            
            IDDocumentJpaController docController = new IDDocumentJpaController(Persistence.createEntityManagerFactory("dbAnagBasePU"));
            docController.create(doc);
            
            PersonJpaController personController = new PersonJpaController(Persistence.createEntityManagerFactory("dbAnagBasePU"));
            try {
                personController.edit(selectedPerson);
                System.out.println("Person: "+selectedPerson.getNome() + " has been updated");
            } catch (Exception ex) {
                Logger.getLogger(NewDocFrame.class.getName()).log(Level.SEVERE, null, ex);
            }
            
            
        }
    }//GEN-LAST:event_jButton1ActionPerformed

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(NewDocFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(NewDocFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(NewDocFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(NewDocFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new NewDocFrame().setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private it.coraci.anag.gui.docs.mr.DocTypeComboBoxModel docTypeComboBoxModel1;
    private it.coraci.anag.gui.docs.mr.DocTypeComboBoxRenderer docTypeComboBoxRenderer1;
    private javax.swing.JButton jButton1;
    private javax.swing.JComboBox jComboBox1;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel2;
    // End of variables declaration//GEN-END:variables
}
